package com.njtoyo.taxi.admin.rest.readfile.customer;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njtoyo.taxi.admin.library.common.util.CopyUtil;
import com.njtoyo.taxi.admin.mapper.master.entity.User;
import com.njtoyo.taxi.admin.mapper.master.mapper.UserMapper;
import com.njtoyo.taxi.admin.rest.presenter.platfrom.DataAuthSqlWhere;
import com.njtoyo.taxi.admin.utils.AuthUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class CustomerQueryListener extends AnalysisEventListener<CustomerQueryData> {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerQueryListener.class);

    private final List<CustomerQueryData> data = new ArrayList<>();
    private final CustomerQueryResult result = new CustomerQueryResult();
    private final UserMapper userMapper;

    public CustomerQueryListener(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public void invoke(CustomerQueryData item, AnalysisContext context) {
        data.add(item);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        result.setUploadCount(data.size());
        List<Long> ids = data.stream().map(CustomerQueryData::getId).collect(Collectors.toList());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.in("id", ids);
        List<User> list = userMapper.selectListByDataAuth(wrapper,AuthUtil.getDataAuthSqlWhere());
        List<CustomerQueryResult.Customer> customers = CopyUtil.copyList(list, CustomerQueryResult.Customer.class);
        List<CustomerQueryData> queryData = CopyUtil.copyList(list, CustomerQueryData.class);
        result.setSuccessCount(list.size());
        result.setSuccessResult(customers);
        data.removeAll(queryData);
        result.setFailCount(data.size());
        result.setFailResult(data);
    }

    public CustomerQueryResult getResult() {
        return result;
    }
}
